package o2o.web.actions.user;

import o2o.dao.VO.user.UserInfoVO;

import java.util.HashSet;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 *
 * @desc : 用户角色辅助类
 * @User: @Created by yangtk
 * @Date: @Date 2019/10/29 14:06
 * @Classname: UserRoleUtils
 * @To change this template use File | Settings | File Templates.
 */
public class UserRoleUtils {
    public static final Integer user_role_ordinary = 1; // 普通用户
    public static final Integer user_role_distribution = 1 << 1; // 分销商

    private static Set<Integer> userRoleData = new HashSet<>();

    static {
        userRoleData.add(user_role_ordinary);
        userRoleData.add(user_role_distribution);
    }

    // 解析角色
    public static void analysisUserRoles(UserInfoVO userInfoVO) {
        if (userInfoVO == null) {
            return;
        }
        Set<Integer> rSet = analysisUserRoles(userInfoVO.getUserRole());
        if (rSet != null) {
            userInfoVO.setUserRoles(rSet);
        }

    }

    public static Set<Integer> analysisUserRoles(Integer oriRole) {
        if (oriRole == null) {
            return null;
        }
        Set<Integer> roles = new HashSet<>();
        for (Integer role : userRoleData) {
            if (validUserRole(oriRole, role)) {
                roles.add(role);
            }
        }
        return roles;
    }

    // 是当前系统的角色类型
    public static boolean isSysUserRole(int role) {
        return userRoleData.contains(role);
    }

    // 设置为某种角色
    public static Integer grantUserRole(Integer oriRole, int role) {
        if (oriRole == null) {
            return role;
        }
        return oriRole | role;
    }

    // 解除某角色
    public static Integer cancelUserRole(Integer oriRole, int role) {
        if (oriRole == null) {
            oriRole = 0;
        }
        return oriRole & (~role);
    }

    // 是否有某种角色
    public static boolean validUserRole(Integer oriRole, int ruleRole) {
        if (oriRole == null) {
            return false;
        }
        return (oriRole & ruleRole) > 0;
    }

    public static void main(String[] args) {
        System.out.println(1 << 1);
        System.out.println(validUserRole(1, user_role_distribution));
        System.out.println(cancelUserRole(3, user_role_distribution));
        System.out.println(grantUserRole(2, user_role_distribution));
    }


}
